package cn.org.itool.ws.framework.ws;

import cn.hutool.core.thread.GlobalThreadPool;
import cn.org.itool.ws.framework.config.NettyProperties;
import cn.org.itool.ws.framework.listener.WsListener;
import cn.org.itool.ws.framework.netty.NettyServer;
import cn.org.itool.ws.framework.protocol.factory.ProtocolServiceFactory;
import cn.org.itool.ws.framework.protocol.service.ProtocolService;
import cn.org.itool.ws.framework.ws.command.CommandHandlerMethodRegistry;
import cn.org.itool.ws.template.AuthTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Log4j2
@Service
public class WsServer {

    public static CommandHandlerMethodRegistry METHOD_REGISTRY;

    public static AuthTemplate AUTH_TEMPLATE;

    public static WsListener WS_LISTENER;

    public static ProtocolService PROTOCOL_SERVICE;
    public static Integer PROTOCOL;

    public static NettyProperties NETTY_PROPERTIES;

    public static ObjectMapper OBJECT_MAPPER;

    @Resource
    private NettyProperties nettyProperties;

    @Resource
    private CommandHandlerMethodRegistry commandHandlerMethodRegistry;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private WsListener wsListener;


    @Value("${i-tool.ws.protocol:0}")
    private Integer protocol;

    @Value("${i-tool.ws.enable:true}")
    private boolean enable;

    private NettyServer nettyServer;

    @Resource
    private AuthTemplate authTemplate;



    @PostConstruct
    private void init() {
        if(!enable) {
            return;
        }
        log.info("init WsServer");
        METHOD_REGISTRY = commandHandlerMethodRegistry;
        NETTY_PROPERTIES = nettyProperties;
        OBJECT_MAPPER = objectMapper;
        PROTOCOL = protocol;

        AUTH_TEMPLATE = this.authTemplate;
        WS_LISTENER = this.wsListener;
        PROTOCOL_SERVICE = ProtocolServiceFactory.getInstance(PROTOCOL);
    }

    public void start() {
        GlobalThreadPool.execute(()->{
            nettyServer = new NettyServer(nettyProperties.getPort());
            nettyServer.run();
            log.info("ws connect url : ws://127.0.0.1:{}{}", nettyProperties.getPort(), nettyProperties.getPath());
        });
    }

    public void stop() {
        if(Objects.nonNull(nettyServer)) {
            try {
                nettyServer.stop();
            }catch (Exception e) {
                log.error("e:", e);
            }

        }
    }
}
